package service.impl;

import utils.MyBatisUtils;
import dao.NotificationMapper;
import entity.Notification;
import service.NotificationService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 通知服务实现类
 */
public class NotificationServiceImpl implements NotificationService {

    @Override
    public void createNotification(Notification notification) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            mapper.insert(notification);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("创建通知失败: " + e.getMessage());
        }
    }

    @Override
    public Notification getNotificationById(Long id) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            return mapper.selectById(id);
        }
    }

    @Override
    public List<Notification> getNotificationsByUserId(Long userId) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            return mapper.selectByUserId(userId);
        }
    }

    @Override
    public int getUnreadCount(Long userId) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            return mapper.countUnreadByUserId(userId);
        }
    }

    @Override
    public void updateNotification(Notification notification) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            mapper.updateById(notification);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("更新通知失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteNotification(Long id) {
        try (SqlSession sqlSession = MyBatisUtils.getSqlSession(false)) {
            NotificationMapper mapper = sqlSession.getMapper(NotificationMapper.class);
            mapper.deleteById(id);
            sqlSession.commit();
        } catch (Exception e) {
            throw new RuntimeException("删除通知失败: " + e.getMessage());
        }
    }
}
    